package com.lingxu.module.redList.service.impl;

import cn.hutool.extra.servlet.ServletUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lingxu.base.common.api.vo.Result;
import com.lingxu.base.common.constant.LogType;
import com.lingxu.base.common.util.EasyExcelUtils;
import com.lingxu.base.config.LogInfoHandler;
import com.lingxu.base.system.common.entity.SysLog;
import com.lingxu.base.system.common.service.ISysLogService;
import com.lingxu.module.database.entity.Model;
import com.lingxu.module.database.entity.ModelRun;
import com.lingxu.module.database.entity.SourceStcHis;
import com.lingxu.module.database.mapper.UseDataBaseMapper;
import com.lingxu.module.redList.entity.*;
import com.lingxu.module.redList.mapper.RedListMapper;
import com.lingxu.module.redList.mapper.RedListTempMapper;
import com.lingxu.module.redList.service.RedListService;
import com.lingxu.module.result.mapper.ResultFeedbackMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @Title: RedListServiceImpl
 * @Package: com.lingxu.module.redList.service.impl
 * @Author: ysj闫世杰
 * @Email: 1105324813@qq.com
 * @Date: Created in 2023/6/15 14:56
 * @Description:
 * @Version: 1.0.0
 */
@Service
public class RedListServiceImpl extends ServiceImpl<RedListMapper, RedList> implements RedListService {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private RedListMapper redListMapper;
    @Autowired
    private RedListTempMapper redListTempMapper;
    @Autowired
    private UseDataBaseMapper useDataBaseMapper;
    @Autowired
    private ResultFeedbackMapper resultFeedbackMapper;

    @Autowired
    private ISysLogService sysLogService;

    @Override
    public Result findRedList(ParamsDTO dto) {
        try {
            if("320801".equals(dto.getCityCode())){
                dto.setCityCode(null);
            }
            if("系统录入".equals(dto.getType())){
                Page<RedListApply> listPage = new Page<>(dto.getPage(),dto.getLimit());
                IPage<RedListApply> redList = redListMapper.findRedApplyList(dto,listPage);

                String content = "在【"+ new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + "，查询了红名单信息列表】";
                new LogInfoHandler().setLogInfoHandler(LogType.LOG_RED_LIST_FIND,content);

                return Result.ok(redList,"查询成功");
            }else if("Excel导入".equals(dto.getType())){
                Page<RedList> listPage = new Page<>(dto.getPage(),dto.getLimit());
                IPage<RedList> redList = redListMapper.findRedListExcel(listPage);

                String content = "在【"+ new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + "，查询了红名单信息列表】";
                new LogInfoHandler().setLogInfoHandler(LogType.LOG_RED_LIST_FIND,content);

                return Result.ok(redList,"查询成功");
            }else  {
                Page<RedList> listPage = new Page<>(dto.getPage(),dto.getLimit());
                IPage<RedList> redList = redListMapper.findRedList(dto,listPage);
                return Result.ok(redList,"查询成功");
            }
        }catch (Exception e){
            logger.error("数据查询异常",e);
            return Result.error("查询异常");
        }
    }

    /**
     * @Author ysj闫世杰
     * @Description 提供查询红名单接口服务
     * @Date 2023/6/19 16:16
     * @Param: keyWord
     * @return com.lingxu.base.common.api.vo.Result
     **/
    @Override
    public Result openFindRedListApi(String keyWord) {
        try {
            return Result.ok(redListMapper.openFindRedListApi(keyWord),"查询成功");
        }catch (Exception e){
            logger.error("数据查询异常",e);
            return Result.error("查询异常");
        }
    }


    @Override
    public void exportRedList(HttpServletResponse response,String cityCode) {
        try {
            if("320800".equals(cityCode)){
                cityCode = null;
            }
            List<RedList> redLists = redListMapper.findListAll(cityCode);
            EasyExcelUtils.exportExcel(redLists,"红名单信息","sheet",RedList.class,"红名单信息.xls",response);
        }catch (Exception e){
            logger.error("操作异常",e);
        }
    }


    @Override
    public void exportMode(HttpServletResponse response) {
        try {
            String fileName = new String("红名单导入模板.xlsx".getBytes("gb2312"), "iso8859-1");
            Resource resource = new ClassPathResource("template/red_list_mode.xlsx");
            InputStream in = resource.getInputStream();
            // 设置输出的格式
            response.reset();
            response.setContentType("application/octet-stream;charset=UTF-8");
            response.addHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
            // 循环取出流中的数据
            byte[] b = new byte[100];
            int len;
            while ((len = in.read(b)) > 0)
                response.getOutputStream().write(b, 0, len);
            in.close();
        }catch (Exception e){
            logger.error("操作异常",e);
        }
    }


    public Result findRedListLog(String startTime,String endTime,Integer limit,Integer page,String type){
        try {
            Page<SysLog> logPage = new Page<>(page,limit);
            IPage<SysLog> pageInfo = redListMapper.findRedListLog(startTime,endTime,logPage,type);
            return Result.ok(pageInfo,"查询成功");
        }catch (Exception e){
            logger.error("数据查询异常",e);
            return Result.error("查询异常");
        }
    }

    @Override
    public void compareToRedList(HttpServletResponse response, HttpServletRequest request, String userId, String realName, String userName) {
        try {
            //与红名单表记录LEFT JOIN
            List<CompareRedList> data = redListMapper.compareToRedList();
            //删除临时比对表记录
            redListTempMapper.deleteAll();
            //导出比对结果
            EasyExcelUtils.exportExcel(data,"红名单比对结果","sheet",CompareRedList.class,
                    "红名单比对结果.xls",response);
            //保存日志记录
            String content = "在【"+ new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + "，比对红名单数据，并导出Excel。】";
            SysLog sysLog = new SysLog();
            sysLog.setUserid(userId);
            sysLog.setCreatetime(new Date());
            sysLog.setLogtype(10);
            sysLog.setLogcontent(content);
            sysLog.setUsername(userName);
            sysLog.setRealname(realName);
            sysLog.setIp(ServletUtil.getClientIP(request));
            sysLogService.save(sysLog);
        }catch (Exception e){
            logger.error("数据查询异常",e);
        }
    }

    //唯一性校验
    @Override
    public int findExistByIdCard(String idcard) {
        return redListMapper.findExistByIdCard(idcard);
    }

    /**
     * @Author ysj闫世杰
     * @Description 查询待审批红名单数量
     * @Date 2023/7/24 15:11
     * @Param: userId
     * @return com.lingxu.base.common.api.vo.Result
     **/
    @Override
    public Result findNeedApprovalCount(ParamsDTO dto) {
        try {
            //查询红名单待审批
            Page<RedListApply> listPage = new Page<>(1,9999);
            IPage<RedListApply> redList = redListMapper.findNeedApprovalList(listPage);
            //二级库待审批
            Page<SourceStcHis> stcHisPage = new Page<>(1,9999);
            IPage<SourceStcHis> database = useDataBaseMapper.findNeedApprovalList(stcHisPage,"0",dto.getCityCode());
            //模型发布待审批
            Page<Model> modelPage = new Page<>(1,9999);
            IPage<Model> model = useDataBaseMapper.findModelApproval(modelPage,"0",null);
            //红名单查看待审批
            Page<ModelRun> modelRun = new Page<>(1,9999);
            IPage<ModelRun> redListRead = useDataBaseMapper.findApprovalRedPerson(modelRun,"0");
            //查询红名单比对待审批
            Page<RedListTemp> tempPage = new Page<>(1,9999);
            IPage<RedListTemp> redListTemp = redListTempMapper.findNeedApprovalList(tempPage,"0");
            //查询成效反馈待审批
            int cou = resultFeedbackMapper.findNeedApprovalCount();
            Map<String,Object> map = new HashMap<>();
            map.put("redList",redList.getTotal());
            map.put("database",database.getTotal());
            map.put("model",model.getTotal());
            map.put("redListRead",redListRead.getTotal());
            map.put("redListTemp",redListTemp.getTotal());
            map.put("resultFeed",cou);

            return Result.ok(map,"操作成功");
        }catch (Exception e){
            logger.error("操作异常",e);
            return Result.error("操作异常");
        }
    }

    @Override
    public Result findNeedApprovalList(Integer page, Integer limit) {
        try {
            Page<RedListApply> applyPage = new Page<>(page,limit);
            IPage<RedListApply> data = redListMapper.findNeedApprovalList(applyPage);
            return Result.ok(data,"查询成功");
        }catch (Exception e){
            logger.error("数据查询异常",e);
            return Result.error("查询异常");
        }
    }
}
